/*
 * The MIT License
 * 
 * Copyright (c) 2008 Comcast Interactive Media
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package cim.sf.core.command.internal;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import cim.sf.core.command.AnnotatedCommands;
import cim.sf.core.command.CommandInvocation;
import cim.sf.core.command.annotations.Command;

import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;

/**
 * 
 * @author <a href="mailto:jeremy_volkman@cable.comcast.com">Jeremy Volkman</a>
 *
 */
public class AnnotatedCommandRegistrar {

    private ArrayList<AnnotatedCommand> commands;
    private BundleContext context = null;
    private List<ServiceRegistration> registeredCommands = null;
    
    public AnnotatedCommandRegistrar(AnnotatedCommands obj) {
        Class<?> clazz = obj.getClass();
        
        commands = new ArrayList<AnnotatedCommand>();

        // Step through this class' methods and look for command methods.
        Method[] methods = clazz.getDeclaredMethods();
        for (Method m : methods) {
            // Make sure this method has the proper signature.
            Class<?>[] paramTypes = m.getParameterTypes();
            if (paramTypes.length != 1 || paramTypes[0] != CommandInvocation.class 
                    || (m.getReturnType() != void.class && m.getReturnType() != int.class)) {
                continue;
            }
            // Check for the Command annotation
            // If it exists, create a Command out of this method.
            Annotation methodAnn = m.getAnnotation(Command.class);
            if (methodAnn instanceof Command) {
                Command cAnn = (Command) methodAnn;
                AnnotatedCommand cmd = new AnnotatedCommand(m, cAnn, obj);
                commands.add(cmd);
            }
        }
        commands.trimToSize();
    }
    
    public void open(BundleContext context) {
        close();
        this.context = context;
        registeredCommands = new ArrayList<ServiceRegistration>(commands.size());
        for (AnnotatedCommand c : commands) {
            Dictionary<String, Object> properties = new Hashtable<String, Object>();
            properties.put("command.path", c.getPath());
            registeredCommands.add(context.registerService(cim.sf.core.command.Command.class.getName(), 
                            c, properties));
        }
    }
    
    public void close() {
        if (context != null && registeredCommands != null) {
            for (ServiceRegistration sr : registeredCommands) {
                try {
                    sr.unregister();
                } catch (IllegalStateException e) {
                    // already unregistered
                }
            }
        }
        context = null;
        registeredCommands = null;
    }
    
    private static class AnnotatedCommand implements cim.sf.core.command.Command {

        private Method method;
        private Command annotation;
        private Object obj;
        
        private AnnotatedCommand(Method method, Command annotation, AnnotatedCommands obj) {
            this.method = method;
            this.annotation = annotation;
            this.obj = obj;
        }
        
        public int execute(CommandInvocation ci) {
            try {
                method.setAccessible(true);
                Object ret = method.invoke(obj, ci);
                if (ret instanceof Integer) {
                    return ((Integer)ret).intValue();
                } else {
                    return 0; // default return value.
                }
            } catch (InvocationTargetException e) {
                if (e.getCause() instanceof RuntimeException) {
                    throw (RuntimeException) e.getCause();
                } else if (e.getCause() != null) {
                    throw new RuntimeException(e.getCause());
                } else {
                    throw new RuntimeException(e);
                }
            } catch (RuntimeException e) {
                throw e;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        public String getDescription() {
            return annotation.description();
        }

        public String getPath() {
            return annotation.path();
        }

        public String[] getUsage() {
            return annotation.usage();
        }
        
    }

}
